<?php

namespace jd_vop\request\order;

/**
 * 7.3 提交订单 skus
 */
class SubmitOrderSkus
{
    /**
     * @var array SubmitOrderSku 数组
     */
    public $list;


    /**
     * 7.3 提交订单 skus
     */
    public function __construct()
    {
        $this->list = [];
    }

    /**
     * 添加商品
     * @param int $skuId 商品SKU
     * @param int $num 数量
     * @param float $price 价格
     * @return bool
     */
    public function add(int $skuId, int $num = 1, float $price = 0): bool
    {
        $flag = false;
        foreach ($this->list as $v) {
            if ($v instanceof SubmitOrderSku) {
                if ($v->getSkuId() == $skuId) {
                    $v->setNum($v->getNum() + $num);
                    $v->setPrice($price);
                    $flag = true;
                    break;
                }
            }
        }
        if (!$flag) {
            if (count($this->list) < 50) {
                $this->list[] = new SubmitOrderSku($skuId, $num, $price);
                $flag = true;
            }
        }
        return $flag;
    }

    /**
     * 减少商品
     * @param int $skuId 商品SKU
     * @param int $num 数量
     */
    public function subtract(int $skuId, int $num = 1)
    {
        foreach ($this->list as $k => $v) {
            if ($v instanceof SubmitOrderSku) {
                if ($v->getSkuId() == $skuId) {
                    $v->setNum($v->getNum() - $num);
                    if ($v->getNum() <= 0) {
                        array_splice($this->list, $k, 1);
                    }
                    break;
                }
            }
        }
    }

    /**
     * 解析数据
     * @return false|string
     */
    public function parse()
    {
        foreach ($this->list as $k => $v) {
            if ($v instanceof SubmitOrderSku) {
                if ($v->getPrice() <= 0) {
                    unset($v->price);
                }
            }
        }
        return json_encode($this->list);
    }
}